import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { PayAPI } from '@/api/pay';
import { savePendingOrderId, getPendingOrderId, clearPendingOrderId } from '@/utils/orderStorage';
import { ElMessage } from 'element-plus';

/**
 * 订单状态管理Store
 */
export const useOrderStore = defineStore('order', () => {
  // 状态
  const currentOrderId = ref<string>('');
  const isPolling = ref<boolean>(false);
  const pollingTimer = ref<NodeJS.Timeout | null>(null);
  const timeoutTimer = ref<NodeJS.Timeout | null>(null);
  const orderStartTime = ref<number>(0);
  const showPaymentSuccess = ref<boolean>(false);
  const paymentSuccessData = ref<any | null>(null);
  const errorRetryCount = ref<number>(0); // 错误重试计数器
  const nexProductInfoUrl = ref(''); // nex商品详情

  // 常量
  const POLLING_INTERVAL = 60 * 1000; // 5秒轮询间隔
  const ORDER_TIMEOUT = 20 * 60 * 1000; // 20分钟超时
  const MAX_ERROR_RETRY = 5; // 最大错误重试次数

  // 计算属性
  const hasActiveOrder = computed(() => currentOrderId.value !== '');
  const isOrderExpired = computed(() => {
    if (!orderStartTime.value) return false;
    return Date.now() - orderStartTime.value > ORDER_TIMEOUT;
  });
  const isMaxRetryReached = computed(() => errorRetryCount.value >= MAX_ERROR_RETRY);
  const retryStatus = computed(() => ({
    current: errorRetryCount.value,
    max: MAX_ERROR_RETRY,
    remaining: MAX_ERROR_RETRY - errorRetryCount.value,
  }));

  /**
   * 开始订单轮询
   * @param orderId 订单ID
   */
  const startOrderPolling = (orderId: string) => {
    console.log('开始全局订单轮询:', orderId);

    // 清除之前的轮询
    stopOrderPolling();

    currentOrderId.value = orderId;
    isPolling.value = true;
    orderStartTime.value = Date.now();
    errorRetryCount.value = 0; // 重置错误计数器

    // 保存到本地存储
    savePendingOrderId(orderId);

    // 立即检查一次状态
    checkOrderStatus();

    // 设置轮询定时器
    pollingTimer.value = setInterval(() => {
      checkOrderStatus();
    }, POLLING_INTERVAL);

    // 设置超时定时器
    timeoutTimer.value = setTimeout(() => {
      console.log('订单轮询超时，停止轮询');
      stopOrderPolling();
      ElMessage.warning('The order has exceeded the deadline...');
    }, ORDER_TIMEOUT);
  };

  /**
   * 检查订单状态
   */
  const checkOrderStatus = async () => {
    if (!currentOrderId.value || !isPolling.value) return;

    try {
      const orderStatus = await PayAPI.getOrderStatus(currentOrderId.value);
      console.log('订单状态==:', orderStatus);

      // 成功获取到状态，重置错误计数
      errorRetryCount.value = 0;

      // 支付成功
      if (orderStatus.status == '1') {
        stopOrderPolling();
        // 支付成功之后弹窗
        showPaymentSuccessModal(orderStatus);
      }
      // 其他状态继续轮询
    } catch (error) {
      console.error('查询订单状态失败:', error);

      // 增加错误计数
      errorRetryCount.value += 1;
      console.log(`订单状态查询失败，重试次数: ${errorRetryCount.value}/${MAX_ERROR_RETRY}`);

      // 如果达到最大重试次数，停止轮询
      if (errorRetryCount.value >= MAX_ERROR_RETRY) {
        console.error('订单状态查询失败次数过多，停止轮询');
        stopOrderPolling();

        return;
      }
    }
  };

  /**
   * 停止订单轮询
   */
  const stopOrderPolling = () => {
    console.log('停止订单轮询');

    if (pollingTimer.value) {
      clearInterval(pollingTimer.value);
      pollingTimer.value = null;
    }

    if (timeoutTimer.value) {
      clearTimeout(timeoutTimer.value);
      timeoutTimer.value = null;
    }

    currentOrderId.value = '';
    isPolling.value = false;
    orderStartTime.value = 0;
    errorRetryCount.value = 0; // 重置错误计数器

    // 清除本地存储
    clearPendingOrderId();
  };

  /**
   * 显示支付成功弹窗
   * @param orderStatus 订单状态
   */
  const showPaymentSuccessModal = (orderStatus: any) => {
    paymentSuccessData.value = {
      order_id: orderStatus.order_id,
      order_type: orderStatus.order_type,
      cover: orderStatus.product.cover,
      pod_name: orderStatus.pod_name,
      nex_need_count: orderStatus.nex_need_count,
    };
    showPaymentSuccess.value = true;
    console.log('显示全局支付成功弹窗:', orderStatus);
  };

  /**
   * 处理支付成功确认
   */
  const handlePaymentSuccessConfirm = () => {
    showPaymentSuccess.value = false;
    paymentSuccessData.value = null;
  };

  /**
   * 处理支付成功弹窗关闭
   */
  const handlePaymentSuccessClose = () => {
    showPaymentSuccess.value = false;
    paymentSuccessData.value = null;
  };

  /**
   * 检查并恢复订单轮询（页面刷新后使用）
   */
  const checkAndResumeOrderPolling = () => {
    const pendingOrderId = getPendingOrderId();
    if (pendingOrderId && !isPolling.value) {
      console.log('发现待支付订单，恢复全局轮询:', pendingOrderId);
      startOrderPolling(pendingOrderId);
    }
  };

  /**
   * 创建新订单
   * @param orderResponse 订单响应
   */
  const createOrder = (orderResponse: any) => {
    console.log('创建新订单:', orderResponse);

    // 保存订单ID到本地存储
    savePendingOrderId(orderResponse.order_id);

    // 开始轮询
    startOrderPolling(orderResponse.order_id);
  };

  // 创建后台订单
  const createOrderHandle = async (params: any) => {
    console.log('创建后台订单:', params);
    try {
      // 显示加载状态
      // 调用创建订单接口
      const orderResponse = await PayAPI.createOrder(params);
      window.open(orderResponse.url, '_blank');
      // 如果是nex 获取当前nex的商品详情
      nexProductInfoUrl.value = window.location.href;
      console.log('nexProductInfoUrl==:', nexProductInfoUrl.value);

      // 使用全局订单store创建订单
      createOrder(orderResponse);
    } catch (error) {
      console.error('创建订单失败:', error);
      ElMessage.error('create order failed...');
    }
  };
  return {
    // 状态
    currentOrderId,
    isPolling,
    showPaymentSuccess,
    paymentSuccessData,
    errorRetryCount,

    nexProductInfoUrl,

    // 计算属性
    hasActiveOrder,
    isOrderExpired,
    isMaxRetryReached,
    retryStatus,

    // 方法
    startOrderPolling,
    stopOrderPolling,
    checkOrderStatus,
    showPaymentSuccessModal,
    handlePaymentSuccessConfirm,
    handlePaymentSuccessClose,
    checkAndResumeOrderPolling,
    createOrder,
    createOrderHandle,
  };
});
